/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.flyco.indicatorsamples;

import com.flyco.pageindicator.anim.select.RotateEnter;
import com.flyco.pageindicator.anim.select.ZoomInEnter;
import com.flyco.pageindicator.anim.unselect.ZoomInExist;
import com.flyco.pageindicator.indicator.FlycoPageIndicator;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.PageSlider;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.util.ArrayList;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 指示器和PageSlider配合使用演示页面
 */
public class MainAbility extends Ability {

    private static final String TAG = MainAbility.class.getName();
    private static final int MSG_BANNER = 0;
    private int[] resIds = {ResourceTable.Media_item1, ResourceTable.Media_item2, ResourceTable.Media_item3, ResourceTable.Media_item4};
    private ArrayList<Component> pageview;
    private PageSlider page;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_main);
        initView();
        page.setProvider(new SamplePageSliderProvider(pageview));
        page.setCurrentPage(0);
        indicator(ResourceTable.Id_indicator_circle);
        indicator(ResourceTable.Id_indicator_square);
        indicator(ResourceTable.Id_indicator_round_rectangle);
        indicator(ResourceTable.Id_indicator_circle_stroke);
        indicator(ResourceTable.Id_indicator_square_stroke);
        indicator(ResourceTable.Id_indicator_round_rectangle_stroke);
        indicator(ResourceTable.Id_indicator_circle_snap);
        indicatorAnim();
        indicatorRes();
    }

    private void initView() {
        page = (PageSlider) findComponentById(ResourceTable.Id_pager);
        pageview = new ArrayList<>();
        PixelMap pixelMap = getPixelMap(this, resIds[0]).get();
        int windowWdith = getWindowWdith(this);
        for (int i = 0; i < resIds.length; i++) {
            Image image = new Image(getContext());
            image.setLayoutConfig(new ComponentContainer.LayoutConfig(windowWdith, windowWdith * pixelMap.getImageInfo().size.height / pixelMap.getImageInfo().size.width));
            image.setScaleMode(Image.ScaleMode.CLIP_CENTER);
            image.setPixelMap(resIds[i]);
            pageview.add(image);
        }
    }

    private EventHandler bannerHandler = new EventHandler(EventRunner.getMainEventRunner()) {
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event.eventId == MSG_BANNER) {
                removeEvent(MSG_BANNER);
                int currentPage = page.getCurrentPage();
                if (currentPage == 3) {
                    currentPage = 0;
                } else {
                    currentPage++;
                }
                page.setCurrentPage(currentPage);
                sendEvent(MSG_BANNER, 2000);
            }
        }
    };

    private FlycoPageIndicator indicator(int indicatorId) {
        final FlycoPageIndicator it = (FlycoPageIndicator) findComponentById(indicatorId);
        it.setPageSlider(page, pageview.size());
        return it;
    }

    private FlycoPageIndicator indicatorAnim() {
        final FlycoPageIndicator itAnim = (FlycoPageIndicator) findComponentById(ResourceTable.Id_indicator_circle_anim);
        // 滑动过度动画与指示器子元素动画只能二选一，setIsSnap(true)代表不要滑动过度动画,要子元素动画
        itAnim.setIsSnap(true)
                .setSelectAnimClass(ZoomInEnter.class)
                .setUnselectAnimClass(ZoomInExist.class)
                .setPageSlider(page, pageview.size());
        return itAnim;
    }

    private FlycoPageIndicator indicatorRes() {
        final FlycoPageIndicator itRes = (FlycoPageIndicator) findComponentById(ResourceTable.Id_indicator_res);
        itRes.setIsSnap(true)
                .setSelectAnimClass(RotateEnter.class)
                .setPageSlider(page, pageview.size());
        return itRes;
    }

    private Optional<PixelMap> getPixelMap(Context context, int id) {
        try {
            String path = context.getResourceManager().getMediaPath(id);
            RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path);
            ImageSource.SourceOptions options = new ImageSource.SourceOptions();
            options.formatHint = "image/png";
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            Resource asset = assetManager.openRawFile();
            ImageSource source = ImageSource.create(asset, options);
            return Optional.ofNullable(source.createPixelmap(decodingOptions));
        } catch (Exception e) {
            Logger.getLogger(TAG).log(Level.SEVERE, e.getMessage());
        }
        return Optional.empty();
    }

    private int getWindowWdith(Context context) {
        return context.getResourceManager().getDeviceCapability().width * context.getResourceManager().getDeviceCapability().screenDensity / 160;
    }

}
